package com.qc.sys.web;

import com.qc.common.mapper.JsonMapper;
import com.qc.common.utils.StringUtils;
import com.qc.common.web.BaseController;
import com.qc.sys.entity.Role;
import com.qc.sys.service.SystemService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 角色Controller
 */
@Controller
@RequestMapping(value = "sys/role")
public class RoleController extends BaseController {

	@Autowired
	private SystemService systemService;
	

	@ModelAttribute("role")
	public Role get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return systemService.getRole(id);
		}else{
			return new Role();
		}
	}
	
	@RequiresPermissions("sys:role:view")
	@RequestMapping(value = {"list", ""})
	public String list(Role role, Model model) {
		List<Role> list = systemService.findAllRole();
		model.addAttribute("list",list);
		setTitle(model, "角色列表");
		return "sys.role.roleList";
	}

	@RequiresPermissions("sys:role:view")
	@RequestMapping(value = "form")
	public String form(Role role, Model model) {
		model.addAttribute("role", role);
		if (StringUtils.isNotBlank(role.getId())) {
			setTitle(model, "角色编辑");
		} else {
			setTitle(model, "角色添加");
		}
		return "sys.role.roleForm";
	}
	
	@RequiresPermissions("sys:role:edit")
	@RequestMapping(value = "save")
	public String save(Role role, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response) {
		if (!beanValidator(model, role)){
			return form(role, model);
		}
		systemService.saveRole(role);
		addMessage(redirectAttributes, "保存角色 [ " + role.getZhName() + " ] 成功");
		redirectAttributes.addFlashAttribute("redirect", request.getContextPath()+"/sys/role");
		return "redirect:/sys/role";
	}

	@RequiresPermissions("sys:role:edit")
	@RequestMapping(value = "saveResp")
	public String saveResp(Role role, Model model,HttpServletResponse response) {
		if (!beanValidator(model, role)){
			return form(role, model);
		}
		systemService.saveRole(role);
		return renderString(response,"保存成功", "text/html;charset=UTF-8");
	}
	
	@RequiresPermissions("sys:role:edit")
	@RequestMapping(value = "delete")

	public String delete(Role role, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		systemService.deleteRole(role.getId());
		addMessage(redirectAttributes, "删除角色成功");
		redirectAttributes.addFlashAttribute("redirect", request.getContextPath()+"/sys/role");
		return "redirect:/sys/role";
	}

}
